<template>
	<view class="edit-home">
		<form @submit="formSubmit" @reset="formReset">
			<tui-list-cell :hover="false">
				<view class="tui-line-cell">
					<view class="tui-title required">姓名</view>
					<input placeholder-class="phcolor" 
					class="tui-input" name="name" 
					v-model="pageData.name"
					placeholder="请输入姓名" maxlength="50" type="text" />
				</view>
			</tui-list-cell>
			<tui-list-cell :arrow="true" class="tui-list" style="justify-content: space-between;padding-right: 60upx;">
				<text class="tui-list-cell-name required">人员类别</text>
				<view class="tui-right">
				  <picker @change="bindPickerChange" :value="typeIndex" range-key="value" :range="typeList" data-key="typeIndex">
				  	<view class="uni-input">{{(typeList[typeIndex] || {}).value || pageData.layer || '请选择人员类别'}}</view>
				  </picker>
				</view>
			</tui-list-cell>
			<tui-list-cell :hover="false">
				<view class="tui-line-cell">
					<view class="tui-title required">性别</view>
					<radio-group class="radio-group" name="sex" v-model="pageData.sex">
						<label class="tui-radio">
							<radio value="0" color="#5677fc" :checked="pageData.sex === '0'"/>男
						</label>
						<label class="tui-radio">
							<radio value="1" color="#5677fc"  :checked="pageData.sex === '1'"/>女
						</label>
					</radio-group>
				</view>
			</tui-list-cell>
			<tui-list-cell :hover="false">
				<view class="tui-line-cell">
					<view class="tui-title required">年龄</view>
					<input placeholder-class="phcolor" 
					class="tui-input" name="age" 
					v-model="pageData.age"
					placeholder="请输入年龄" maxlength="50" type="text" />
				</view>
			</tui-list-cell>
			<tui-list-cell :hover="false">
				<view class="tui-line-cell">
					<view class="tui-title required">证件号码</view>
					<input placeholder-class="phcolor" 
					class="tui-input" name="idCard" 
					v-model="pageData.idCard"
					placeholder="请输入身份证号码" maxlength="50" type="text" />
				</view>
			</tui-list-cell>
			<view class="line-back"></view>
			<tui-list-cell :hover="false">
				<view class="tui-line-cell">
					<view class="tui-title required">电话号码</view>
					<input placeholder-class="phcolor"
					 class="tui-input" name="link" 
					 v-model="pageData.link"
					 placeholder="请输入姓名" maxlength="50" type="text" />
				</view>
			</tui-list-cell>
			<tui-list-cell>
				<view class="tui-line-cell">
					<view class="tui-title required">验证码</view>
					<input placeholder-class="tui-phcolor"
					class="tui-input" 
					name="vcode" 
					placeholder="请输入验证码" maxlength="50" type="text" />
					<tui-button size="mini" :type="type" shape="circle" :plain="true" :disabled="disabled" @click="btnSend">{{btnText}}</tui-button>
				</view>
			</tui-list-cell>
			<view class="line-back"></view>
			<tui-list-cell :hover="false">
				<view class="tui-line-cell" style="display: flex;flex-flow: column;align-items: flex-start;">
					<view class="tui-title required" style="margin-bottom: 20upx;">家庭地址</view>
					<textarea placeholder-class="phcolor" 
					v-model="pageData.remark"
					name="remark"
					class="tui-input" placeholder="请输入家庭地址" maxlength="50" type="text" />
				</view>
			</tui-list-cell>
			<view class="tui-footer">
				<tui-button class="tui-btn tui-danger tui-fillet" hover-class="tui-danger-hover" formType="submit">保存</tui-button>
			</view>
		</form>
		
	</view>
</template>

<script>
	const form = require("../../../components/utils/formValidation.js")
	import tuiListCell from "@/components/list-cell/list-cell"
	import tuiButton from "@/components/button/button"
	const util = require('@/utils/util.js')
	import constant from "@/constant"
	import Java110Context from '@/context/Java110Context.js'
	const pageDataConst = {
		name:'',
		sex:'',
		age:'',
		idCard:'',
		link:'',
		remark:''
	}
	export default {
		components: {
			tuiListCell,
			tuiButton
		},
		data() {
			return {
				pageData:{
				  ...pageDataConst
				},
				typeList:[
					{
						key:'1001',
						index:0,
						value:'业主'
					},
					{
						key:'1002',
						index:1,
						value:'家庭成员'
					},
					{
						key:'1003',
						index:2,
						value:'租客'
					},
					{
						key:'1004',
						index:3,
						value:'其他'
					},
				],
				typeIndex:'',
				btnText: "获取验证码",
				disabled: false,
				type: "primary",
				ownerId:'',
				communityId:''
			}
		},
		onLoad(option){
			this.pageData = option || {
				...pageDataConst
			};
			this.typeIndex = (this.typeList.filter(item => item.key === option.ownerTypeCd)[0] || {}).index || '';
			let _that = this;
			    this.java110Context.getOwner(function(_owner){
			      _that.setData({
			        ownerId: _owner.memberId,
			        communityId: _owner.communityId
			      });
			    });
		},
		mounted() {
		   uni.showNavigationBarLoading()	
		   setTimeout(() => {
			    uni.hideNavigationBarLoading()
		   },1000)
		},
		methods:{
			bindPickerChange: function(e) {
				let { key } = e.target.dataset;
				this[key] = e.target.value
			},
			setData(obj){
				Object.keys(obj).forEach(key => {
					this[key] = obj[key]
				})
			},
			getRandom: function(seconds) {
				uni.showLoading({
					mask: true,
					title: '请稍候...'
				})
				const _that = this;
				let obj = {
				      tel: this.pageData.link
				};
				// return new Promise((resolve,reject) => {
					Java110Context.request({
					      url: constant.url.userSendSms,
					      header: Java110Context.getHeaders(),
					      method: "POST",
					      data: obj, //动态数据
					      success: function(res) {
					        //成功情况下跳转
					        if (res.statusCode == 200) {
					          uni.hideLoading()
					          _that.doLoop(seconds);
					          return;
					        }
							_that.btnText = "获取验证码";
							_that.disabled = false;
							_that.type = "primary";
					        uni.hideLoading()
					        uni.showToast({
					          title: res.data,
					          icon: 'none',
					          duration: 2000
					        });
					      },
					      fail: function(e) {
							  _that.btnText = "获取验证码";
							  _that.disabled = false;
							  _that.type = "primary";
					        uni.hideLoading()
					        _that.tui.toast("服务器异常了")
					      }
					    });
				// })
				
			},
			doLoop: function(seconds) {
				// let code = this.getRandom(6);
				// this.tui.toast('您本次的验证码是：' + code, 5000);
				seconds = seconds ? seconds : 60;
				this.btnText = seconds + "s后获取";
				// this.code = code
				let countdown = setInterval(() => {
					if (seconds > 0) {
						this.btnText = seconds + "s后获取"
							--seconds;
					} else {
						this.btnText = "获取验证码";
						this.disabled = false;
						this.type = "primary";
						clearInterval(countdown);
					}
				}, 1000);
			},
			btnSend: function() {
				if (util.isNullOrEmpty(this.pageData.link)) {
					this.tui.toast('请输入手机号码');
					return
				} else if (!util.isMobile(this.pageData.link)) {
					this.tui.toast('请输入正确的手机号码');
					return
				}
				this.disabled = true;
				this.btnText = "请稍候...";
				this.type = "gray"
			
				// setTimeout(() => {
				this.getRandom(60)
				// }, 500)
			},
			backList(e) {
				//返回并刷新上一页面
				// console.log(e)
				let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
				let curRoute = routes[routes.length - 3] // 获取当前页面路由，也就是最后一个打开的页面路由
				// console.log(curRoute)
				curRoute.getTable(1);
				uni.navigateBack({
				    delta: 2,
				})
			},
			formSubmit(e){
				let rules = [{
					name: "name",
					rule: ["required", "minLength:2", "maxLength:10"], //可使用区间，此处主要测试功能
					msg: ["请输入用户名", "用户名必须2个或以上字符", "用户名不能超过10个字符"]
				},{
					name:"sex",
					rule: ["required"],
					msg: ["请选择性别"]
				},{
					name: "link",
					rule: ["required", "isMobile"],
					msg: ["请输入手机号", "请输入正确的手机号"]
				},{
					name: "idCard",
					rule: ["required", "isIdCard"],
					msg: ["请输入身份证号码", "请输入正确的身份证号码"]
				},{
					name: "vcode",
					rule: ["required"],
					msg: ["请输入验证码"]
				}];
				//进行表单检查
				let formData = e.detail.value;
				let checkRes = form.validation(formData, rules);
				let _that = this;
				if (!checkRes) {
					let obj = {
					  "sex": formData.sex,
					  "name": formData.name,
					  "link": formData.link,
					  "remark": formData.remark,
					  "ownerId": this.ownerId,
					  "userId": this.pageData.userId || '',
					  "ownerTypeCd": formData.ownerTypeCd || this.pageData.ownerTypeCd || '1002',
					  "age": formData.age,
					  "memberId": this.pageData.memberId,
					  "communityId":this.communityId,
					  "idCard":formData.idCard
					};
					uni.showLoading({
					        title: '提交中',
					      });
						  let url = constant.url.saveOwner;
						  if(this.pageData.memberId){
							  url = constant.url.updateOwner;
						  }
					      Java110Context.request({
					        url: url, 
					        header: Java110Context.getHeaders(),
					        method: "POST",
					        data: obj,
					        // data:obj, //动态数据
					        success: function(res) {
					
					          if (res.statusCode == 200) {
					            uni.hideLoading();
					            _that.backList();
					            return;
					          }
					
					          uni.hideLoading();
					          uni.showToast({
					            title: res.data,
					            icon: 'none',
					            duration: 2000
					          });
					        },
					        fail: function (e) {
					          uni.hideLoading();
					          uni.showToast({
					            title: "服务器异常了",
					            icon: 'none',
					            duration: 2000
					          })
					        }
					      });
						
				}else{
					uni.showToast({
						title: checkRes,
						icon: "none"
					});
				}
				console.log(formData)
			}
		}
	}
</script>

<style>
	.edit-home{
		/* height: calc(100vh); */
		overflow-y: auto;
		padding-bottom: 10upx;
		padding-top: 30upx;
		box-sizing: border-box;
		position: relative;
		background-color: rgb(247, 249, 251);
	}
	.edit-home .tui-footer{
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		padding: 30upx 40upx;
		background-color: #FFFFFF;
	}
	.edit-home .container {
		padding: 20rpx 0 50rpx 0;
	}
	
	.edit-home .tui-line-cell {
		width: 100%;
		box-sizing: border-box;
		display: flex;
		align-items: center;
	}
	
	.edit-home .tui-title {
		line-height: 32rpx;
		flex-shrink: 0;
	}
	.edit-home .line-back{
		margin-top: 30upx;
	}
	.edit-home .tui-input {
		font-size: 32rpx;
		color: #333;
		padding-left: 20rpx;
		flex: 1;
	}
	
	.edit-home .radio-group {
		margin-left: auto;
		transform: scale(0.8);
		transform-origin: 100% center;
		flex-shrink: 0;
	}
	
	.edit-home .tui-radio {
		display: inline-block;
		padding-left: 28rpx;
		font-size: 36rpx;
		vertical-align: middle;
	}
	
	
	.edit-home .tui-btn-box {
		padding: 40rpx 50rpx;
		box-sizing: border-box;
	}
	
	.edit-home .btn-gray {
		margin-top: 30rpx;
	}
	
	.edit-home .tui-tips {
		padding: 30rpx;
		color: #999;
		font-size: 24rpx;
	}
</style>
